﻿using System;
using System.Web;
using System.Web.Security;
using Presenter_SSResourceManager;

namespace WebView_SSResourceManager
{
    public partial class Login : System.Web.UI.Page, IViewLogin
    {
        PresenterLogin presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            ManagerRoles.CreateRoles();
            presenter = new PresenterLogin(this);
            RegisterHyperLink.NavigateUrl = ResolveUrl("Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]));
        }

        protected void Login_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
        {
            presenter.LoginUser();
            Response.Redirect("~/");
        }

        public string GetUserName()
        {
            return LoginUser.UserName;
        }

        public int GetPassword()
        {
            return LoginUser.Password.GetHashCode();
        }

        public void SetUserId(Guid id)
        {
            Request.Cookies.Remove("UID");
            var idCookie = new HttpCookie("UID");
            idCookie.Value = id.ToString();
            idCookie.Expires = DateTime.Now.AddDays(3);
            Response.Cookies.Add(idCookie);
        }

        public void SetUserRole(string userName, string role)
        {
            if (!Roles.IsUserInRole(userName, role))
            {
                Roles.AddUserToRole(userName, role);
            }
        }

        public void PerformLogging(string userName)
        {
            FormsAuthentication.SetAuthCookie(userName, true);
            FormsAuthentication.RedirectFromLoginPage(userName, true);
        }

        public void Filure(string errorText)
        {
            LoginUser.FailureText = errorText;
        }
    }
}
